package com.king.framework.base.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.king.common.constant.Constants;
import com.king.common.exception.AssertHelper;
import com.king.common.utils.text.StringUtils;
import com.king.common.utils.uuid.SnowFlakeUtil;
import com.king.framework.base.domain.YyTreeEntity;
import com.king.framework.base.service.YyTreeService;

public abstract class YyTreeServiceImpl<M extends BaseMapper<T>, T extends YyTreeEntity, ID extends Serializable> extends YyBaseServiceImpl<M, T, ID>  implements YyTreeService<T, ID> {

    
	@Override
	public void beforeAdd(T entity) throws Exception {
		AssertHelper.getInstance().checkNullException(entity.getParentid(), "父节点不能为空");
		
		if(entity.getId() == null){
			entity.setId(SnowFlakeUtil.getInstance().nextId());
		}
		T parent = findByPK((ID)entity.getParentid());
		AssertHelper.getInstance().checkNullException(parent, "不存在父节点:" + entity.getParentid());
		String nodepath = parent.getNodepath();
		entity.setNodepath(nodepath.concat(Constants.TREE_PATH_SPLIT).concat(String.valueOf(entity.getId())));
		super.beforeAdd(entity);
	}

	
	
	
	@Override
	public void beforeDelete(T entity) throws Exception {
		List<T> children = findByParentid(entity.getId());
		AssertHelper.getInstance().checkException(CollectionUtils.isNotEmpty(children), "存在子节点不能删除");
		super.beforeDelete(entity);
	}




	@Override
	public List<T> findByParentid(Long parentid) {
		QueryWrapper<T> queryWrapper = new QueryWrapper<>();
//		queryWrapper.eq("ss", SsEnum.NORMAL.getKey());
		queryWrapper.eq("parentid", parentid);
		queryWrapper.orderByAsc("showorder");
		return list(queryWrapper);
	}




	@Override
	protected void processData(T entity) throws Exception {
		if(entity != null&& entity.getParentid() != null){
			T parent = getById((ID)entity.getParentid());
			if(parent != null){
				entity.setParentname(parent.getNodename());
			}
		}
		super.processData(entity);
	}




	@Override
	protected void processData(List<T> list) throws Exception {
		if(CollectionUtils.isEmpty(list)){
			return;
		}
		Set<ID> parentIds = (Set<ID>) list.stream().map(T::getParentid).collect(Collectors.toSet());
		List<T> parentList = findByPKS(parentIds);
		Map<Long, T> parentMap = parentList.stream().collect(Collectors.toMap(obj -> obj.getId(), Function.identity()));
		for(T t : list){
			T parent = parentMap.get(t.getParentid());
			if(parent == null){
				t.setParentname("");
				continue;
			}
			t.setParentname(parent.getNodename());
		}
		super.processData(list);
	}




	@Transactional(readOnly = false, rollbackFor = { Exception.class })
	@Override
	public void resetNodepath() throws Exception {
        List<T> list = findAll();
        if (list != null) {
        	Map<Long,T> map = list.stream().collect(Collectors.toMap(obj -> obj.getId(), Function.identity()));
        	List<String> nodepaths = null;
            for(T t : list){
            	nodepaths = new ArrayList<String>();
            	nodepaths.add(t.getId().toString());
            	if(t.getParentid() == null){
            		t.setParentid(0L);
            	}
            	T p = map.get(t.getParentid());
            	if(p != null){
            		nodepaths.add(p.getId().toString());
            		recursionParent(p, map, nodepaths);
            	}
            	Collections.reverse(nodepaths);
            	
            	UpdateWrapper<T> updateWrapper = new UpdateWrapper<T>();
            	System.out.println(StringUtils.join(nodepaths, Constants.TREE_PATH_SPLIT));
            	updateWrapper.set(Constants.TREE_COLUMN_NODEPATH, StringUtils.join(nodepaths, Constants.TREE_PATH_SPLIT));
            	updateWrapper.eq("id", t.getId());
            	update( updateWrapper);
            }
        }
    }


	private void recursionParent(T t, Map<Long, T> map, List<String> nodepaths) {
		T p = map.get(t.getParentid());
    	if(p == null){
    		return;
    	}
    	nodepaths.add(p.getId().toString());
    	recursionParent(p, map, nodepaths);
	}
	
}
